# -*- coding: utf-8 -*-
# @Time    : 2021/11/16 18:50 
# @Author  : BrandonGT
# @FileName: install.py 
# -----------------------------------------------------
# Python 自带Module
import os
import sys
import shutil
import getpass
import zipfile
import pythoncom

# Python 第三方Module
import win32com.client

# Python 自定义Module

# -----------------------------------------------------


def install(dir):
    """拷贝ZIP至指定路径，并解压"""
    # root = os.path.abspath(os.getcwd())
    root = dir
    new_user = os.path.expanduser("~")
    print(f"安装包根目录：{root}")
    package = f"{root}/Launcher_Pack.zip"
    target_path = f"{new_user}/BD_DCC_LAUNCHER"
    print(f"安装目标目录：{target_path}")
    target_package = f"{target_path}/Launcher_Pack.zip"
    target_install_bat = f"{target_path}/install.bat"
    target_install_py = f"{target_path}/install.py"

    # # 验证路径是否存在，不存在则创建，存在则清空后创建
    # if os.path.exists(target_path):
    #     print(f"安装目录已存在，清除旧目录内容...")
    #     shutil.rmtree(target_path)
    # os.makedirs(target_path)
    # print(f"创建新安装目录...")

    # 拷贝ZIP至本地路径
    shutil.copy(package, target_path)
    print(f"拷贝ZIP至安装目录...")

    # 解压ZIP
    with zipfile.ZipFile(target_package, mode='a') as f:
        f.extractall(target_path)
        print(f"解压ZIP内容...")

    # 解压完成后，删除ZIP
    os.remove(target_package)
    os.remove(target_install_bat)
    os.remove(target_install_py)
    print(f"移除ZIP...")
    print(f"启动器安装完成...")


def create_shortcut():
    """创建执行文件的桌面快捷方式"""
    new_user = os.path.expanduser("~")
    lnk_root = f"{new_user}/Desktop/鹰角网络CG组启动器.lnk"
    excute_root = f"{new_user}/BD_DCC_LAUNCHER/bin/launcher.exe"
    excute_folder = f"{new_user}/BD_DCC_LAUNCHER/bin"
    icon = f"{new_user}/BD_DCC_LAUNCHER/resource/icon/lnk_icon.ico"

    shell = win32com.client.Dispatch("WScript.Shell")
    shortcut = shell.CreateShortCut(lnk_root)
    shortcut.Targetpath = excute_root
    shortcut.WorkingDirectory = excute_folder
    shortcut.IconLocation = icon
    # shortcut.WindowStyle = 7  # 7 - Minimized, 3 - Maximized, 1 - Normal
    shortcut.save()
    print("桌面快捷方式已生成...")


def open_install_folder():
    """打开安装目录"""
    new_user = os.path.expanduser("~")
    target_path = f"{new_user}/BD_DCC_LAUNCHER/bin"
    os.startfile(target_path)


if __name__ == '__main__':
    arg1 = sys.argv[1]
    print(arg1)
    install(arg1)
    create_shortcut()
    # open_install_folder()